<?php
namespace app\wxapplet\controller;

use think\Request;
use app\yxwadmin\controller\Admin;
use app\common\logic\UploadLogic;
use app\common\mns\Queue;
use think\cache\driver\Redis;
use app\common\httpdown\HttpRequest;
use app\common\wx\Token;
use app\common\wx\Temp;

/** 
* 模版管理
* @author      xieliang<xieliang007@qq.com>
* @version     $1.0$ 
* @since       1.0 
*/
class Template extends Admin
{
    /**
     * 模版管理首页
     */
    public function index()
    {
        $appletlist = model("WechatAppletModel")->where("product_code","photo_albums_bless")->select();
        $template = new Temp();
        $templatedata = array();
        
        
        $list = model("TemplateModel")->alias('a')->field('a.original_id')
        ->join('WxApplet b','a.original_id=b.original_id','LEFT')
        ->where("product_code","photo_albums_bless")->group("original_id")->select();

        foreach($list as $original_id){
            //获取模版信息
            $templatelist = $template->mylist($original_id['original_id'],0,20);
            foreach($templatelist['list'] as $tmp){
                $templatedata[$tmp["template_id"]] = $tmp["title"];
            }
        }

        $this->assign('appletlist',$appletlist);        
        $this->assign('templatelist', json_encode($templatedata));
        return $this->view->fetch('template/index');
    }

    /**
     * 获取小程序模版信息
     */
    public function getTempList(){
        $original_id = input("original_id");
        $template = new Temp();
        $templatelist = $template->mylist($original_id,0,20);        
        return json($templatelist);        
    }

    /**
     * 获取模版管理消息数据列表
     */
    public function getList(){
        $limit = input('post.limit','0','trim');
        $offset = input('post.offset','0','trim');
        $sortName = input('post.sortName','id','trim');
        $sortOrder = input('post.sortOrder','asc','trim');
        $keyword = input('post.keyword','','trim');
        $originalid = input('post.original_id','','trim');

        $where['product_code'] = "photo_albums_bless";
        if(!empty($keyword)){
            $where['temp_name']=array('like','%'.$keyword.'%');
        }
        if(!empty($originalid)){
            $where['original_id'] = $originalid;
        }

        $count = model('TemplateModel')->alias('a')
        ->join('WxApplet b','a.original_id=b.original_id','LEFT')->where($where)->count(); //查询满足要求的总记录数
        $list = model('TemplateModel')->alias('a')->field('a.id,a.original_id,b.name as applet_name,a.template_id,a.pageurl,a.temp_name,a.addtime')
        ->join('WxApplet b','a.original_id=b.original_id','LEFT')->where($where)->order([$sortName=>$sortOrder])->limit($offset,$limit)->select();
        
        $data['total'] = $count;
        $data['rows'] = $list;
        return $data;
    }

    /**
     * 新增模版
     */
    public function add(){
        if (Request::instance()->isPost()){
            $data=input('post.');
            $data['template_data'] = urldecode($data['template_data']);
            $data['addtime'] = time();
            $data['uptime'] = $data['addtime'];

            if($id=model("TemplateModel")->allowField(true)->save($data)){
                $ret["code"]=0;
                $ret['msg']="保存成功";
                return $ret;
            }else{
                $ret["code"]=1;
                $ret['msg']="保存失败";
                return $ret;
            }
        }else{
            $appletlist = model("WechatAppletModel")->where("product_code","photo_albums_bless")->select();
            $this->assign('appletlist',$appletlist);
            return $this->view->fetch('template/add');
        }
    }

    /**
     * 编辑模版
     */
    public function edit(){
         //判断提交方式 做不同的处理
         if (Request::instance()->isPost()){
            $data=input('post.');
            $data['template_data'] = urldecode($data['template_data']);
            $data['uptime'] = time();
            $res=model('TemplateModel')->allowField(true)->save($data,['id' => $data['id']]);
            if($res){
                $ret["code"]=0;
                $ret['msg']="修改成功";
            }
            else{
                $ret["code"]=1;
                $ret['msg']="修改失败";
            }
            return $ret;
        }else{
            $id = input('get.id');
            $data = model('TemplateModel')->find($id);

            $appletlist = model("WechatAppletModel")->where("product_code","photo_albums_bless")->select();
            $this->assign('appletlist',$appletlist);
            $this->assign('data',$data);            
            return $this->view->fetch('template/edit');
        }
    }    

    /**
     * 删除模版
     */
    public function del(){
        if ( Request::instance()->isPost() ) {
            $id = input('post.id/d');
            if ($id > 0) {
                $ct = model('TemplateTaskModel')->where('temp_id',$id)->count();
                if($ct>0){
                    $ret["code"]=1;
                    $ret['msg']="删除成功,消息任务中存在该模版";
                }else{
                    $res = model('TemplateModel')->where('id',$id)->delete();
                    if($res){
                        $ret["code"]=0;
                        $ret['msg']="删除成功";
                    }
                    else{
                        $ret["code"]=1;
                        $ret['msg']="删除失败";
                    }
                }
            }else{
                $ret["code"]=1;
                $ret['msg']="删除失败,参数错误!";
            }
            return $ret;
        }
    }

    /**
     * 模版消息发送任务页面
     */
    public function task(){
        return $this->view->fetch('template/task');        
    }

    /**
     * 获取模版消息任务数据集合
     */
    public function gettaskList(){
        $limit = input('post.limit','0','trim');
        $offset = input('post.offset','0','trim');
        $sortName = input('post.sortName','id','trim');
        $sortOrder = input('post.sortOrder','asc','trim');
        $keyword = input('post.keyword','','trim');

        $where['product_code'] = "photo_albums_bless";
        if(empty($keyword)){
            $where['task_name']=array('like','%'.$keyword.'%');
        }

        $count = model('TemplateTaskModel')->alias('a')->join('Template b','a.temp_id=b.id','LEFT')
        ->join('WxApplet c','b.original_id=c.original_id','LEFT')->where($where)->count(); //查询满足要求的总记录数
        $list = model('TemplateTaskModel')
        ->alias('a')->field('a.*,b.temp_name,c.name applet_name')
        ->join('Template b','a.temp_id=b.id','LEFT')
        ->join('WxApplet c','b.original_id=c.original_id','LEFT')
        ->where($where)->order(array($sortName=>$sortOrder))
        ->limit($offset,$limit)->select();        
        
        $data['total'] = $count;
        $data['rows'] = $list;
        return $data;
    }

    /**
     * 添加模版消息发送任务
     */
    public function addtask(){
        if (Request::instance()->isPost()){
            $data=input('post.');
            $data['execute_time'] = strtotime($data['execute_time']);
            $data['addtime'] = time();
            $data['uptime'] = $data['addtime'];
            $rest = model("TemplateTaskModel")->allowField(true)->save($data);            
            if($rest){
                $ret["code"]=0;
                $ret['msg']="保存成功";
                $id = model("TemplateTaskModel")->getLastInsID();
                $templateinfo = model('TemplateTaskModel')->alias('a')->field('b.*')->where("a.id",$id)
                ->join('Template b','a.temp_id=b.id','LEFT')->find();
                //发送MQ消息
                $queue = new Queue();
                $msgdata = json_encode(array(
                    "Action"=>"Add",
                    "MsgData"=>array(
                        "taskid"=>$id,
                        "begin_time"=>date('Y-m-d H:i:s',$data["execute_time"]),
                        "original_id"=>$templateinfo['original_id'],
                        "template_id"=>$templateinfo['template_id'],
                        "template_data"=>$templateinfo['template_data'],
                        "emphasis"=>$templateinfo['emphasis'],
                        "pageurl"=>$templateinfo['pageurl']
                    )
                ));                
                $queue->SendMessage($msgdata);
                return $ret;
            }else{
                $ret["code"]=1;
                $ret['msg']="保存失败";
                return $ret;
            }
        }else{
            return $this->view->fetch('template/addtask');
        }
    }

    /**
     * 编辑模版消息发送任务
     */
    public function edittask(){
        //判断提交方式 做不同的处理
        if (Request::instance()->isPost()){
            $data=input('post.');
            $data['execute_time'] = strtotime($data['execute_time']);
            $data['uptime'] = time();

            $templateinfo = model('TemplateTaskModel')->alias('a')->field('b.*')->where("a.id",$data["id"])
                ->join('Template b','a.temp_id=b.id','LEFT')->find();
            $res=model('TemplateTaskModel')->allowField(true)->save($data,['id' => $data['id']]);
            if($res){
                $ret["code"]=0;
                $ret['msg']="修改成功";
                //发送MQ消息
                $queue = new Queue();
                $msgdata = json_encode(array(
                    "Action"=>"Update",
                    "MsgData"=>array(
                        "taskid"=>$data["id"],
                        "begin_time"=>date('Y-m-d H:i:s',$data["execute_time"]),
                        "original_id"=>$templateinfo['original_id'],
                        "template_id"=>$templateinfo['template_id'],
                        "template_data"=>$templateinfo['template_data'],
                        "emphasis"=>$templateinfo['emphasis'],
                        "pageurl"=>$templateinfo['pageurl']                      
                    )
                ));
                $queue->SendMessage($msgdata);
            }
            else{
                $ret["code"]=1;
                $ret['msg']="修改失败";
            }
            return $ret;
        }else{
            $id = input('get.id');
            $data = model('TemplateTaskModel')->alias('a')->field('a.*,b.temp_name')
            ->join('Template b','a.temp_id=b.id','LEFT')->find($id);           
            $this->assign('data',$data);           
            return $this->view->fetch('template/edittask');
        }
    }

    /**
     * 删除模版消息任务
     */
    public function deltask(){
        if ( Request::instance()->isPost() ) {
            $id = input('post.id/d');
            if ($id > 0) {
                $templateinfo = model('TemplateTaskModel')->alias('a')->field('a.execute_time,b.*')->where("a.id",$id)
                ->join('Template b','a.temp_id=b.id','LEFT')->find();
                $res = model('TemplateTaskModel')->where('id',$id)->delete();
                if($res){
                    $ret["code"]=0;
                    $ret['msg']="删除成功";
                    //发送MQ消息
                    $queue = new Queue();          
                    $msgdata = json_encode(array(
                        "Action"=>"Delete",
                        "MsgData"=>array(
                            "taskid"=>$id,
                            "begin_time"=>date('Y-m-d H:i:s',$templateinfo["execute_time"]),
                            "original_id"=>$templateinfo['original_id'],
                            "template_id"=>$templateinfo['template_id'],
                            "template_data"=>$templateinfo['template_data'],
                            "emphasis"=>$templateinfo['emphasis'],
                            "pageurl"=>$templateinfo['pageurl']                      
                        )
                    ));
                    $queue->SendMessage($msgdata);
                }
                else{
                    $ret["code"]=1;
                    $ret['msg']="删除失败";
                }
            }else{
                $ret["code"]=1;
                $ret['msg']="删除失败,参数错误!";
            }
            return $ret;
        }
    }

    /**
     * 选择发送模版页面
     */
    public function selTemplate(){
        return $this->view->fetch('template/seltemplate');
    }

    public function test(){
        $appletlist = model("WechatAppletModel")->select();
        //print_r();        
        $token = new Token();
        $access_token = $token->getAccessToken($appletlist[0]['original_id']);
        print_r($access_token);
        exit;
    }

    public function testmsg(){
        $queue = new Queue();
        $queue->SendMessage(json_encode(array(
            "Action"=>"Update",
            "MsgData"=>array("taskid"=>1,"begin_time"=>"2018-02-13 18:00:00","template_id"=>"22222","template_data"=>"1333","pageurl"=>"page/index/index")
        )));
    }
}